﻿using System;
using System.Web.Mvc;
using System.Web.Routing;
using Castle.MicroKernel;

namespace Wolfbyte.Core.Mvc.Factories
{
    public class MicroKernelControllerFactory : IControllerFactory
    {
        private readonly IKernel Kernel;

        public MicroKernelControllerFactory(IKernel Kernel)
        {
            this.Kernel = Kernel;
        }

        #region IControllerFactory Members

        public IController CreateController(RequestContext context, string controllerName)
        {
            if (context == null)
                throw new ArgumentException("RequestContext is null", "context");

            var key = controllerName.ToLower() + "controller";
            return Kernel.Resolve(key, typeof(IController)) as IController;
        }

        public void DisposeController(IController controller)
        {
            var disposable = controller as IDisposable;
            if (disposable != null)
                disposable.Dispose();
        }

        #endregion
    }
}
